from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
from Login.models import User
from utils.jwttool import jwtTool
from home.models import CommunityPost

class CustomJWTAuthentication(BaseAuthentication):
    def authenticate(self, request):
        print("==== 认证开始 ====")
        print("请求头：", request.headers)
        auth = request.headers.get('Authorization')
        token = None
        if auth and auth.startswith('Bearer '):
            token = auth[7:]
        print("提取到的token：", token)
        if not token:
            token = request.GET.get('token') or request.POST.get('token')
        print("最终token：", token)
        if not token:
            print("没有token，返回None")
            return None
        try:
            payload = jwtTool.checktoken(token)
            print("payload:", payload)
            user_id = payload.get('userid')
            user = User.objects.get(id=user_id)
            user.is_authenticated = True
            print("认证通过，user:", user)
            return (user, None)
        except Exception as e:
            print("认证失败:", e)
            raise exceptions.AuthenticationFailed(f'认证失败: {str(e)}')

    def post(self, request):
        post_id = request.data.get('post_id')
        user = request.user
        print("当前用户id:", user.id)
        try:
            post = CommunityPost.objects.get(id=post_id)
            print("帖子作者id:", post.user.id)
        except Exception as e:
            print("查找帖子异常:", e)
        # ...后续逻辑... 